//
//  DesignBiddingViewController.m
//  ForestPack
//
//  Created by jimmy on 2018/8/8.
//  Copyright © 2018年 郑洲. All rights reserved.
//

///设计师投标上传稿件界面
#import "DesignBiddingViewController.h"
#import "UIView+Utils.h"
#import "AddImgButton.h"

@interface DesignBiddingViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,CTAssetsPickerControllerDelegate>

@property (nonatomic,strong)  BaseTableView   * tableView;
@property (nonatomic,strong)  UITextField     * nameTextF;
@property (nonatomic,strong)  AddImgButton    * addPicsBtn;
@property (nonatomic,strong)  ThemeButton     * submitBtn;
@property (nonatomic,strong)  UITextView      * describeTextV;
@property (nonatomic,strong)  NSMutableArray  * detailPicsArray;
@property (nonatomic,assign)  NSInteger         imageCount;
@property (nonatomic,copy)    NSString        * detailPicsUrl;
@property (nonatomic, strong) NSMutableArray<NSString *> *detailPicsUrlArray;


@end

@implementation DesignBiddingViewController

- (NSMutableArray *)detailPicsArray
{
    if (_detailPicsArray == nil) {
        _detailPicsArray = [[NSMutableArray alloc] init];
    }
    return _detailPicsArray;
}

- (NSMutableArray *)detailPicsUrlArray
{
    if (_detailPicsUrlArray == nil) {
        _detailPicsUrlArray = [[NSMutableArray alloc] init];
    }
    return _detailPicsUrlArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setTitle:@"上传稿件"];
    
    [self setTableViewUI];
}

-(void)setTableViewUI
{
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = TABLEVIEW_BACKGROUNDCOLOR;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:self.tableView];
    
}

-(void)submitClick
{
    if (self.nameTextF.text.length <= 0) {
        [HttpManager showNoteMsg:@"请填写产品名称"];
        return;
    }
    if (self.detailPicsArray.count <= 0) {
        [HttpManager showNoteMsg:@"请上传不超过9张的作品"];
        return;
    }
    if (self.describeTextV.text.length <= 0) {
        [HttpManager showNoteMsg:@"请填写不超过300字的作品描述"];
        return;
    }
    [self uploadPics];
//    [self uploadAllData];
    
}

-(void)uploadPics
{
    WeakObj(self);
    [HttpManager uploadImageArr:self.detailPicsArray success:^(id successResponse) {
        
        selfWeak.detailPicsArray = successResponse;
        
        [selfWeak uploadAllData];
    }];
}

#pragma mark - 上传填写的稿件信息
-(void)uploadAllData
{
    if (self.detailPicsUrlArray.count <= 0) {
        return;
    }
    
    NSString * detail_pic = @""; ///, [0], [1]
    for (NSString * urlStr in self.detailPicsUrlArray) {
        if ([detail_pic isEqualToString:@""]) {
            detail_pic = urlStr;
        }else{
            detail_pic = [NSString stringWithFormat:@"%@,%@",detail_pic, urlStr]; /// [0], [1]
        }
    }
    NSString *url = [NSString stringWithFormat:@"%@app/designer_submission",REQUESTHEADER];//添加商品
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    [dict setValue:[FPLoginAndRegisterTools getToken] forKey:@"token"];
    [dict setValue:@"order_id" forKey:@"order_id"];//order_id
    [dict setValue:self.nameTextF.text forKey:@"design_finished_name"];//产品名称
    [dict setValue:self.describeTextV.text forKey:@"content"];//产品描述
    [dict setValue:detail_pic forKey:@"detail_pic"];//设计产品详情图（两个url之间以逗号隔开）
    [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [HttpManager showNoteMsg:@"提交成功"];
            [self.navigationController popViewControllerAnimated:true];
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

-(void)addPicsClick
{
    self.imageCount = 9 - self.detailPicsArray.count;
    [self alterIconPortrait];
}

#pragma mark----- 选择弹出框
-(void)alterIconPortrait
{
    //弹出提示框
    __weak typeof(self)weakSelf = self;
    //初始化提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //按钮：拍摄
    [alert addAction:[UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf openCamare];
    }]];
    //按钮：从手机相册选择
    [alert addAction:[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        [weakSelf openAlbum];
    }]];
    //按钮：取消，类型：UIAlertActionStyleCancel
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 打开相册
-(void)openAlbum
{
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        
        if (status != PHAuthorizationStatusAuthorized) {
            return ;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            // init Picker弹出图片选择界面
            CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
            //隐藏空相册
            picker.showsEmptyAlbums = NO;
            //允许显示图片选中后的顺序
            picker.showsSelectionIndex = YES;
            //选择需要弹出的相册，一般我们只需要弹出相机胶卷和自定义相册即可
            picker.assetCollectionSubtypes = @[
                                               @(PHAssetCollectionSubtypeSmartAlbumUserLibrary),
                                               @(PHAssetCollectionSubtypeAlbumRegular)
                                               ];
            // picker delegate
            picker.delegate = self;
            // present picker
            [self presentViewController:picker animated:YES completion:nil];
        });
    }];
}

#pragma mark - 打开相机
-(void)openCamare
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.allowsEditing = YES;
    picker.delegate = self;
    
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate  图片处理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSLog(@"Picker returned successfully.");
    //    将选择的图片在imageView上显示
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:1 inSection:0];
    [self.detailPicsArray addObject:image];
    indexPath=[NSIndexPath indexPathForRow:1 inSection:0];
    
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    //处理完毕，回到个人信息页面
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    NSLog(@"Picker was cancelled");
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 设置图片最多选九张
-(BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
{
    NSInteger max = self.imageCount;
    if (picker.selectedAssets.count < max) return YES;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"注意" message:[NSString stringWithFormat:@"最多选择%ld张图片",(long)max] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action];
    //一定要用picker 不能用self 因为当前显示在最上面的控制器是picker 而不是self
    [picker presentViewController:alert animated:YES completion:nil];
    
    return NO;
}

#pragma mark - 选择完毕的时候调用
- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    // 关闭图片选择界面
    [picker dismissViewControllerAnimated:YES completion:nil];
    //选择图片时的配置项 (如果不写配置项 会导致请求的图片尺寸出现问题)
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.resizeMode = PHImageRequestOptionsResizeModeExact;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    
    //遍历图片选择的图片显示成九宫格样式
    for (NSInteger i = 0; i < assets.count; i ++) {
        PHAsset *asset = assets[i];
        CGFloat scale = UIScreen.mainScreen.scale;
        CGSize size = CGSizeMake(asset.pixelWidth / scale, asset.pixelHeight / scale);
        
        //请求图片 (需要先用图片管理员请求图片数据 请求完成后 在block里添加图片)
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            WeakObj(self);
            
            [selfWeak.detailPicsArray addObject:result];
        }];
    }
    
    [self.tableView reloadData];
    
}

#pragma mark - tableView的delegate和datasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 2;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return ScreenX375(44);
        }else{
            return ScreenX375(45) + (self.detailPicsArray.count / 3 + 1) * ScreenX375(110);
//            图片的大小始80*80 左右间隔是：(SCREEN_WIDTH - 240 )/4;
        }
    }else{
        return ScreenX375(200);
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return ScreenX375(10);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    return view;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            UITableViewCell *cell = [[UITableViewCell alloc] init];
            cell.textLabel.text = @"作品名称：";
            self.nameTextF = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - ScreenX375(100), ScreenX375(10), ScreenX375(100), ScreenX375(24))];
            self.nameTextF.textAlignment = NSTextAlignmentLeft;
            self.nameTextF.font = Kfont(14);
            [cell addSubview:self.nameTextF];
            return cell;
        }else{
            static NSString *cellId = @"detailImgCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            for (UIView *subView in cell.subviews) {
                [subView removeFromSuperview];
            }
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(13), ScreenX375(130), ScreenX375(20))];
            if (self.detailPicsArray) {
                label.text = [NSString stringWithFormat:@"作品详情：（%lu/9）",(unsigned long)self.detailPicsArray.count];
            }
            label.text = @"作品详情：（0/9）";
            label.textAlignment = NSTextAlignmentLeft;
            label.font = Kfont(14);
            [cell addSubview:label];
            
            CGFloat margin = (SCREEN_WIDTH - ScreenX375(26) - ScreenX375(330)) / 2;
            for (int i = 0; i < self.detailPicsArray.count; i++) {
                
                CGFloat x = i % 3 * (ScreenX375(110) + margin) + ScreenX375(13);
                CGFloat y = i / 3 * ScreenX375(120) + ScreenX375(45);
                UIImageView * imageV = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, ScreenX375(110), ScreenX375(110))];
                imageV.image = self.detailPicsArray[i];
                [cell addSubview:imageV];
            }
            
            if (self.detailPicsArray.count != 9) {
                self.addPicsBtn = [[AddImgButton alloc] initWithFrame:CGRectMake(self.detailPicsArray.count % 3 * (ScreenX375(110) + margin) + ScreenX375(13), self.detailPicsArray.count / 3 * ScreenX375(120) + ScreenX375(45), ScreenX375(110), ScreenX375(110))];
                
                [self.addPicsBtn addTarget:self action:@selector(addPicsClick) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:self.addPicsBtn];
            }
            return cell;
//            self.addPicsBtn.frame = CGRectMake(ScreenX375(13), label.bottom + ScreenX375(15), ScreenX375(110), ScreenX375(110));
        }
    }else{
        static NSString *cellId = @"describeCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(13), ScreenX375(130), ScreenX375(20))];
        label.text = @"作品描述：";
        label.textAlignment = NSTextAlignmentLeft;
        label.font = Kfont(14);
        [cell addSubview:label];
        
        self.describeTextV = [[UITextView alloc] initWithFrame:CGRectMake(ScreenX375(13), label.bottom + ScreenX375(15), SCREEN_WIDTH - ScreenX375(26), 150)];
        self.describeTextV.text = @"请写作品描述(0/300)字数";
        self.describeTextV.delegate = self;
        self.describeTextV.textAlignment = NSTextAlignmentLeft;
        self.describeTextV.font = Kfont(14);
        self.describeTextV.layer.borderWidth = 1;
        self.describeTextV.layer.borderColor = RGB_COLOR(220,220,220).CGColor;
        [cell addSubview:self.describeTextV];
        return cell;
        
        self.submitBtn = [[ThemeButton alloc] initWithFrame:CGRectMake(ScreenX375(13), self.describeTextV.bottom + ScreenX375(30), SCREEN_WIDTH - ScreenX375(26), ScreenX375(44))];
        [self.submitBtn addTarget:self action:@selector(submitClick) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:self.submitBtn];
    }
    
}

-(void)textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@"请写作品描述(0/300)字数"]) {
        textView.textColor = [UIColor blackColor];
        textView.text = @"";
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    if (textView.text.length < 1) {
        textView.textColor = REXADECIMALCOLOR(@"#999999");
        textView.text = @"请写作品描述(0/300)字数";
    }
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:true];
}

@end
